package com.jinyi.wwdeng.ui.steps.fragment

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.pickerview.builder.TimePickerBuilder
import com.jinyi.pickerview.listener.CustomListener
import com.jinyi.pickerview.listener.OnTimeSelectListener
import com.jinyi.pickerview.view.TimePickerView
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.FragmentStepCommonBinding
import com.jinyi.wwdeng.network.HttpBaseParams.addCommonParams
import com.jinyi.wwdeng.pro.ProFragment
import com.jinyi.wwdeng.ui.steps.act.StepListAct
import com.jinyi.wwdeng.ui.steps.adapter.StepCommonAdapter
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import com.jinyi.wwdeng.utils.popupwindow.ListCenterPopupWindow
import com.jinyi.wwdeng.utils.recyclerview.LinearSpacingItemDecoration
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程通用列表样式
 */
class StepCommonFragment(val data: JSONObject): ProFragment() {
    lateinit var binding: FragmentStepCommonBinding

    //内容列表
    var mCommonAdapter: StepCommonAdapter? = null
    var mSelectPosition = -1

    //出生日期选择
    var pvStartDateView: TimePickerView? = null

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentStepCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        initRecyclerView()
    }

    override fun initListener() {
        //下一步
        binding.btnNext.setOnClickListener {
            if (!isAllowSubmit()){
                showToast(getString(R.string.submit_error))
                return@setOnClickListener
            }

            val params = JSONObject().addCommonParams().apply {
                put("path",data.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<mCommonAdapter!!.itemCount){
                val item = mCommonAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    params.put(item.optString("paramName"),item.optJSONObject("selectItem").optString("value"))
                }
            }
            HHLog.e(">>>>>>提交数据>>>>>>>"+params)
            val act = context as StepListAct
            act.onSubmitRequest(params)

            TrackEventUtils.logEvent(String.format(TrackEventType.CLICK.CLICK_STEP_XX_NEXT,data.optString("stepTitle")),"")
        }
    }

    override fun initData() {
        val dataList = arrayListOf<JSONObject>()
        val dataArray = data.optJSONArray("dataList")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()){
                dataList.add(dataArray.optJSONObject(i))
            }
        }
        mCommonAdapter!!.data = dataList
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRecyclerView() {
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = App.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        mCommonAdapter = StepCommonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mCommonAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mCommonAdapter!!.setOnItemChildClickListener(onItemClickListener)
    }

    /**
     * 选择
     */
    private val onItemClickListener = BGAOnItemChildClickListener { parent, childView, position ->
        binding.root.clearFocus()
        mSelectPosition = position
        val item = mCommonAdapter!!.getItem(position)
        when(item.optString("action")){
            "DATE_PICK" -> {//时间选择
                showBirthDialog()
            }
            "SELECT"->{//选择
                val dataList = arrayListOf<JSONObject>()
                val dataArray = item.optJSONArray("values")
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
                showSelectPopupwindow(childView,dataList)
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = ListCenterPopupWindow(requireContext())
        selectPopup.setWindowWidth(view.width + App.dp2px(10f))
        selectPopup.setSelectItemListener(object : ListCenterPopupWindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = mCommonAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                mCommonAdapter!!.notifyItemChanged(mSelectPosition)

                TrackEventUtils.logEvent(String.format(TrackEventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),data!!.optString("value"))
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, binding.root)
        selectPopup.setBrandList(dataList)
    }

    /**
     * 选择出生日期
     */
    private fun showBirthDialog(){
        if(pvStartDateView == null){
            //当前日期
            var curtDate = Calendar.getInstance()
            var startDate = Calendar.getInstance()
            var endDate = Calendar.getInstance()
            startDate.set(1900,0,1)

            pvStartDateView = TimePickerBuilder(context, object : OnTimeSelectListener{
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                override fun onTimeSelectString(date: Date?, showDate: String?) {
                    val value = SimpleDateFormat("yyyy-MM-dd").format(date!!)
                    //可根据需要自行截取数据显示
                    val item = mCommonAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",showDate)
                    obj.put("value",value)
                    item.put("selectItem",obj)
                    mCommonAdapter!!.notifyItemChanged(mSelectPosition)

                    TrackEventUtils.logEvent(String.format(TrackEventType.CLICK.CLICK_STEP_XX_SELECT,item.optString("paramName")),value)
                }
            })
                .setDate(curtDate) //默认选中
                .setRangDate(startDate, Calendar.getInstance()) //可选择时间范围
                .setLayoutRes(R.layout.dialog_birth, object : CustomListener {
                    override fun customLayout(v: View?) {
                        val ivClose = v!!.findViewById<ImageView>(R.id.ivClose)
                        ivClose.setOnClickListener {
                            pvStartDateView!!.dismiss()
                        }
                        //确定
                        val btnDone = v!!.findViewById<TextView>(R.id.btnDone)
                        btnDone.setOnClickListener {
                            pvStartDateView!!.returnData()
                            pvStartDateView!!.dismiss()
                        }
                    }
                })
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3f)
                .setTextXOffset(40, 40, 40, 40, 40, 40)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(ContextCompat.getColor(requireContext(), R.color.color_08252c)) //设置选中项文字颜色
                .setTextColorOut(ContextCompat.getColor(requireContext(),R.color.color_9ca8ab))//默认颜色
                .setContentTextSize(16)
                .isAlphaGradient(true)
                .setItemVisibleCount(3)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                .build()
            val dialog = pvStartDateView!!.dialog
            if (dialog != null){
                val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)
                params.leftMargin = 0
                params.rightMargin = 0
                pvStartDateView!!.dialogContainerLayout.setLayoutParams(params)
                val dialogWindow = dialog.window
                if (dialogWindow != null) {
                    dialogWindow.setWindowAnimations(com.jinyi.pickerview.R.style.picker_view_scale_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.CENTER)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView!!.show()
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<mCommonAdapter!!.itemCount){
            val item = mCommonAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(String.format(TrackEventType.PAGE.PAGE_STEP_COMMON_XX_START,data.optString("stepTitle")),"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(String.format(TrackEventType.PAGE.PAGE_STEP_COMMON_XX_END,data.optString("stepTitle")),"")
    }
}